# -*- coding: utf-8 -*-

import sys
from io import BytesIO
from PySide import QtGui,QtCore
import scipy as spy
import pyqtgraph as pg
from .EQSignal_UI_D import Ui_EQSignal_
from .About_D import Ui_About_
# from .EQSignal import EQSignal
from copy import deepcopy

class AutoPen(object):
    colors = ["b", "g", "r", "c", "m", "y"]
    n = 6
    i = -1
    color = "b"
    pen = pg.mkPen(color, width=2)

    def __iter__(self):
        return self

    def next(self):
        self.i += 1
        if self.i > self.n-1:
            self.i = 0
        self.color = self.colors[self.i]
        self.pen = pg.mkPen(self.color, width=2)
        return self.pen

    def reset(self):
        self.i = -1

class Ui_About(QtGui.QWidget,Ui_About_):
    """docstring for Ui_ABOUT"""
    def __init__(self, parent=None):
        super(Ui_About, self).__init__(parent)
        self.setupUi(self)

class Ui_EQSignal(QtGui.QMainWindow, Ui_EQSignal_):

    """Ui_EQSignal"""

    def __init__(self, parent=None):
        super(Ui_EQSignal, self).__init__(parent)
        self.setupUi(self)
        # self.eqs = EQSignal()
        self.initViewTH()
        self.initViewSP()
        self.initViewFFT()
        # self.initTable()
        self.fileName = ""
        self.about = Ui_About()
        self.textEditSPA = QtGui.QTextEdit()
        self.textEditSPA.resize(400,600)

        # self.setupConnection()

    def setupConnection(self):

        self.actionNGA_Record.triggered.connect(self.readNGAthenPlotTH)
        self.actionPlain_Text.triggered.connect(self.readTXTthenPlotTH)
        self.actionAbout.triggered.connect(self.about.show)
        self.actionCalculate_Spectra.triggered.connect(self.calSPthenPlotSP)
        self.ApplyAdjust.clicked.connect(self.adjustthenPlotTH)
        self.RSPA.clicked.connect(self.calSPthenPlotSP)
        self.ViewASP.clicked.connect(self.calASPthenPlotASP)
        self.keepOriginal.stateChanged.connect(self.plotTH)

        self.Norm.clicked.connect(self.NormthenPlotTH)
        self.RecoverN.clicked.connect(self.recoverthenPlotTH)
        self.setTB.clicked.connect(self.getTrimIndice)
        self.DoTrim.clicked.connect(self.trimthenPlotTH)
        self.Recover.clicked.connect(self.recoverthenPlotTH)

        self.XS_lin_0.clicked.connect(self.changeXS_SP)
        self.XS_log_0.clicked.connect(self.changeXS_SP)
        self.XS_lin.clicked.connect(self.changeXS_ASP)
        self.XS_log.clicked.connect(self.changeXS_ASP)

        self.VDTH.clicked.connect(self.viewDataTH)
        self.VDSP.clicked.connect(self.viewDataSP)
        self.CDR.activated.connect(self.viewDataSPA)
        self.CDR2.activated.connect(self.viewDataSP)
        self.FSP.activated.connect(self.FFTPSD)
        self.DR.textChanged.connect(self.updateCDR)

        self.SPATON.stateChanged.connect(self.plotSP)

    def initViewTH(self):
        accPlot = self.graphicsViewTH.addPlot(0,0,title="Acceleration")
        accPlot.showGrid(x=True, y=True)
        # accPlot.addLegend()
        # accPlot.legend.close()
        # accPlot.setLabels(bottom="time (s)")
        velPlot = self.graphicsViewTH.addPlot(1,0,title="Velocity")
        velPlot.showGrid(x=True, y=True)
        # velPlot.addLegend()
        # velPlot.legend.close()
        # velPlot.setLabels(bottom="time (s)")
        dispPlot = self.graphicsViewTH.addPlot(2,0,title="Displacement")
        dispPlot.showGrid(x=True, y=True)
        # dispPlot.addLegend()
        # dispPlot.legend.close()
        dispPlot.setLabels(bottom="time (s)")

    def initViewFFT(self):

        fftPlot = self.graphicsViewFFT.addPlot(0,0,title="Fourier Amplitude Spectrum")
        # fftPlot.setLogMode(x=True)
        fftPlot.showGrid(x=True, y=True)
        fftPlot.setLabels(left="Fourier Amplitude",bottom="Frequency (Hz)")
        fftPlot.enableAutoRange()

    def initViewSP(self):

        spPlot = self.graphicsViewSP.addPlot(0,0,title="Acceleration Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()
        spPlot.setLabels(left="Response Acceleration",bottom="Period (s)")

        spPlot = self.graphicsViewASP.addPlot(0,0,title="Acceleration Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()

        spPlot = self.graphicsViewASP.addPlot(0,1,title="Velocity Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()

        spPlot = self.graphicsViewASP.addPlot(1,0,title="Displacement Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()

        spPlot = self.graphicsViewASP.addPlot(1,1,title="Input Energy Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()

    def initTable(self):
        self.tableTH = EQTableWidget(spy.zeros((2048,4)))
        self.tableTH.setHeader(["Time","Acceleration","Velocity","Displacement"])
        self.tableSP = EQTableWidget(spy.zeros((2048,5)))
        self.tableSP.setHeader(["Period","SPA","SPV","SPD","SPE"])
        self.tableSPA = EQTableWidget(spy.zeros((2048,2)))
        self.tableSPA.setHeader(["Period","SPA"])

    def viewDataTH(self):
        # self.tableTH.setData(self.getTHData())
        # self.tableTH.setWindowTitle("Time Series Data")
        # self.tableTH.show()
        data = spy.vstack((self.eqs.t,self.eqs.acc,self.eqs.vel,self.eqs.disp)).T
        Data = BytesIO()
        spy.savetxt(Data,data,fmt="%12.6f",
            header="%12s\t%12s\t%12s\t%12s"%("Time","Acceleration",
                "Velocity","Displacement"),
            delimiter="\t")
        self.textEditTH.clear()
        self.textEditTH.setPlainText(Data.getvalue().decode()[2:])
        self.tabWidget.setCurrentIndex(4)
        Data.close()

    def viewDataSP(self):
        # self.tableSP.setData(self.getSPData())
        # self.tableSP.show()
        i = self.CDR2.currentIndex()
        data = spy.vstack((self.eqs.sp[i].SPT,self.eqs.sp[i].SPA,self.eqs.sp[i].SPV,self.eqs.sp[i].SPD,self.eqs.sp[i].SPE)).T
        Data = BytesIO()
        spy.savetxt(Data,data,fmt="%12.6f",
            header="%12s\t%12s\t%12s\t%12s\t%12s"%("Period","SPA","SPV","SPD","SPE"),
            delimiter="\t")
        self.textEditSP.clear()
        self.textEditSP.setPlainText(Data.getvalue().decode()[2:])
        self.tabWidget.setCurrentIndex(4)
        Data.close()

    def viewDataSPA(self):
        # self.tableSPA.setData(self.getSPAData())
        
        i = self.CDR.currentIndex()

        data = spy.vstack((self.eqs.sp[i].SPT,self.eqs.sp[i].SPA)).T
        Data = BytesIO()
        spy.savetxt(Data,data,fmt="%14.8f",
            header="%14s\t%14s"%("Period","SPA"),
            delimiter="\t")
        self.textEditSPA.clear()
        self.textEditSPA.setPlainText(Data.getvalue().decode()[2:])
        self.textEditSPA.show()

        self.textEditSPA.setWindowTitle("zeta=%.2f"%self.eqs.sp[i].Zeta)
        # self.tableSPA.show()
        Data.close()

    # def getTHData(self):
    #     Data = spy.vstack((self.eqs.t,self.eqs.acc,self.eqs.vel,self.eqs.disp)).T
    #     return Data

    def NormthenPlotTH(self):
        self.eqs.norm()
        self.plotTH()
    
    def updateCDR(self):
        self.CDR.clear()
        self.CDR2.clear()
        self.CDRfit.clear()
        DRs = self.DR.text().replace(" ","").split(",")
        self.CDR.addItems(self.DRs)
        self.CDRfit.addItems(self.DRs)
        self.DRs = ["Damping Ratio : "+dr for dr in DRs]
        self.CDR2.addItems(self.DRs)

    # def getSPData(self):
    #     i = self.CDR.currentIndex()
    #     Data = spy.vstack((self.eqs.sp[i].SPT,self.eqs.sp[i].SPA,self.eqs.sp[i].SPV,self.eqs.sp[i].SPD,self.eqs.sp[i].SPE)).T
    #     return Data

    # def getSPAData(self):
    #     i = self.CDR.currentIndex()
    #     Data = spy.vstack((self.eqs.sp[i].SPT,self.eqs.sp[i].SPA)).T
    #     return Data
    
    def readNGAthenPlotTH(self):
        self.getNGAFileName()
        self.eqs.readNGAFile(self.fileName)
        self.plotTH()
        self.tabWidget.setCurrentIndex(0)
        self.VDTH.setEnabled(True)

    def readTXTthenPlotTH(self):
        self.getTXTFileName()

        dt = QtGui.QInputDialog.getDouble(self, "Time Interval", "dt = ", value=0.02, decimals=3)[0]
        self.eqs.readTXTFile(self.fileName,dt)
        self.plotTH()
        self.tabWidget.setCurrentIndex(0)
        self.VDTH.setEnabled(True)

    def getTrimIndice(self):
        thd1 = self.THD1.value()
        thd2 = self.THD2.value()

        iStart, iStop = self.eqs.getTrimIndice(thd1, thd2)
        self.iStart.setValue(iStart)
        self.iStop.setValue(iStop)

    def trimthenPlotTH(self):
        iStart = max(self.iStart.value()-1,0)
        iStop  = min(self.iStop.value()-1,self.eqs.n-1)
        self.eqs.trim(iStart,iStop)
        self.plotTH()

    def recoverthenPlotTH(self):
        self.eqs.recover()
        self.plotTH()

    def adjustthenPlotTH(self):

        filt = self.Filt.isChecked()
        detr = self.Detrend.isChecked()
        tadj = self.TAdjust.isChecked()

        curr = False

        if filt:
            order = self.FOrder.value()
            f1 = self.Freq1.value()
            f2 = self.Freq2.value()
            btype = self.BandType.currentText()
            self.eqs.filt(order, f1, f2, btype, curr)
            curr = True

        if detr:
            oh = self.OHigh.value()
            ol = self.OLow.value()
            BLAM = self.DetrendMethod.currentText()

            if BLAM == "AccDetrend":
                self.eqs.detrendAcc(oh,ol,curr)
            elif BLAM == "Modified":
                self.eqs.baseLineCorr(oh,ol,curr)
            else:
                pass
            curr = True

        if tadj:
            ntp = self.NTP.value()
            TAM = self.TAMethod.currentText()

            if TAM == "Disp":
                self.eqs.targetDispCorr(ntp,curr)
            elif TAM == "DispVel":
                pass
            elif TAM == "DispVelAcc":
                pass
            else:
                pass
            curr = True

        if not curr:
            self.eqs.a2vd(curr)

        self.plotTH()

    def calSPthenPlotSP(self):
        self.getParaSP()
        self.eqs.getSpectra()
        self.plotSP()
        self.tabWidget.setCurrentIndex(2)
        self.CDR.setEnabled(True)

    def calASPthenPlotASP(self):
        self.getParaSP()
        self.eqs.getAllSpectra()
        self.plotASP()
        self.tabWidget.setCurrentIndex(3)

    def clearLegend(self, legend):
        legend_label_texts = []
        for sample, label in legend.items:
            legend_label_texts.append(label.text)

        for text in legend_label_texts:
            legend.removeItem(text)

    def changeXS_SP(self):
        X_LOG = self.XS_log_0.isChecked()
        self.graphicsViewSP.getItem(0,0).setLogMode(x=X_LOG)

    def changeXS_ASP(self):
        X_LOG = self.XS_log.isChecked()
        self.graphicsViewASP.getItem(0,0).setLogMode(x=X_LOG)
        self.graphicsViewASP.getItem(1,0).setLogMode(x=X_LOG)
        self.graphicsViewASP.getItem(0,1).setLogMode(x=X_LOG)
        self.graphicsViewASP.getItem(1,1).setLogMode(x=X_LOG)

    def plotTH(self):
        kpo = self.keepOriginal.isChecked()

        accItem = self.graphicsViewTH.getItem(0,0)
        accItem.clear()
        # self.clearLegend(accItem.legend)
        # accItem.legend.show()
        if kpo: accItem.plot(self.eqs.t,self.eqs.acc_raw,pen=0.5,name="Original")
        accItem.plot(self.eqs.t,self.eqs.acc,pen="b",name="Adjusted")

        velItem = self.graphicsViewTH.getItem(1,0)
        velItem.clear()
        # self.clearLegend(velItem.legend)
        # velItem.legend.show()
        if kpo: velItem.plot(self.eqs.t,self.eqs.vel_raw,pen=0.5,name="Original")
        velItem.plot(self.eqs.t,self.eqs.vel,pen="b",name="Adjusted")

        dispItem = self.graphicsViewTH.getItem(2,0)
        dispItem.clear()
        # self.clearLegend(dispItem.legend)
        # dispItem.legend.show()
        if kpo: dispItem.plot(self.eqs.t,self.eqs.disp_raw,pen=0.5,name="Original")
        dispItem.plot(self.eqs.t,self.eqs.disp,pen="b",name="Adjusted")

        self.plotFFT()

    def FFTPSD(self):
        i = self.FSP.currentIndex()
        if i == 0:
            self.plotFFT()
        elif i == 1:
            self.plotPSD()
        else:
            pass

    def plotFFT(self):
        self.eqs.fft()
        FFTItem = self.graphicsViewFFT.getItem(0,0)
        FFTItem.clear()
        FFTItem.setTitle("Fourier Amplitude Spectrum")
        FFTItem.setLabels(left="Fourier Amplitude",bottom="Frequency (Hz)")
        n = len(self.eqs.freq)/2
        FFTItem.plot(self.eqs.freq[:n], abs(self.eqs.accf[:n]), pen="b")

    def plotPSD(self):
        self.eqs.fft()
        FFTItem = self.graphicsViewFFT.getItem(0,0)
        FFTItem.clear()
        FFTItem.setTitle("Power Spectral Density (Welch's method)")
        FFTItem.setLabels(left="PSD",bottom="Frequency (Hz)")
        FFTItem.plot(self.eqs.psd[0], abs(self.eqs.psd[1]), pen="b")

    def plotSP(self):
        SPItem = self.graphicsViewSP.getItem(0,0)
        SPItem.clear()
        self.clearLegend(SPItem.legend)
        SPItem.legend.show()
        if self.DM.currentText() == "linear":
            SPItem.setLogMode(x=False)
            self.XS_lin_0.setChecked(True)
            self.XS_log_0.setChecked(False)
        elif self.DM.currentText() == "log":
            SPItem.setLogMode(x=True)
            self.XS_lin_0.setChecked(False)
            self.XS_log_0.setChecked(True)

        cl = AutoPen()
        for sp in self.eqs.sp:
            SPItem.plot(sp.SPT,sp.SPA,pen=cl.next(),name="&zeta; = %.2f"%sp.Zeta)
            if self.SPATON.isChecked():
                SPItem.plot(sp.SPT,sp.SPAT*self.eqs.peak(),pen=pg.mkPen(cl.color,width=2,dash=[5,5]))

    def plotASP(self):
        PenA = AutoPen()
        PenV = AutoPen()
        PenD = AutoPen()
        PenE = AutoPen()

        SPAItem = self.graphicsViewASP.getItem(0,0)
        SPAItem.clear()
        self.clearLegend(SPAItem.legend)
        SPAItem.legend.show()
        if self.DM.currentText() == "linear":
            SPAItem.setLogMode(x=False)
            self.XS_lin.setChecked(True)
            self.XS_log.setChecked(False)
        elif self.DM.currentText() == "log":
            SPAItem.setLogMode(x=True)
            self.XS_lin.setChecked(False)
            self.XS_log.setChecked(True)

        SPVItem = self.graphicsViewASP.getItem(0,1)
        SPVItem.clear()
        self.clearLegend(SPVItem.legend)
        SPVItem.legend.show()
        if self.DM.currentText() == "linear":
            SPVItem.setLogMode(x=False)
        elif self.DM.currentText() == "log":
            SPVItem.setLogMode(x=True)

        SPDItem = self.graphicsViewASP.getItem(1,0)
        SPDItem.clear()
        self.clearLegend(SPDItem.legend)
        SPDItem.legend.show()
        if self.DM.currentText() == "linear":
            SPDItem.setLogMode(x=False)
        elif self.DM.currentText() == "log":
            SPDItem.setLogMode(x=True)

        SPEItem = self.graphicsViewASP.getItem(1,1)
        SPEItem.clear()
        self.clearLegend(SPEItem.legend)
        SPEItem.legend.show()
        if self.DM.currentText() == "linear":
            SPEItem.setLogMode(x=False)
        elif self.DM.currentText() == "log":
            SPEItem.setLogMode(x=True)

        for sp in self.eqs.sp:
            SPAItem.plot(sp.SPT,sp.SPA,pen=PenA.next(),name="zeta = %.2f"%sp.Zeta)
            SPVItem.plot(sp.SPT,sp.SPV,pen=PenV.next(),name="zeta = %.2f"%sp.Zeta)
            SPDItem.plot(sp.SPT,sp.SPD,pen=PenD.next(),name="zeta = %.2f"%sp.Zeta)
            SPEItem.plot(sp.SPT,sp.SPE,pen=PenE.next(),name="zeta = %.2f"%sp.Zeta)

    def getTXTFileName(self):
        fd = QtGui.QFileDialog()
        self.fileName = fd.getOpenFileName(self, "file", ".", "*.txt", "Plain Text File (*.txt *.TXT)")[0]

    def getNGAFileName(self):
        fd = QtGui.QFileDialog()
        self.fileName = fd.getOpenFileName(self, "file", ".", "*.at2", "PEER Record File (*.at2 *.AT2)")[0]

    def getParaSP(self):
        Zeta = [float(zi) for zi in self.DR.text().split(",")]
        Tstart = self.TS.value()
        Tstop  = self.TL.value()
        NP = self.NP.value()
        DM = self.DM.currentText()
        SM = self.SM.currentText()
        PD = self.PD.isChecked()
        Tg = self.Tg.value()
        self.eqs.setupSpectra(NP,Tstart,Tstop,DM,Zeta,SM,PD)
        for sp in self.eqs.sp:
            sp.getCodeSpectra(Tg)

    def fitSpectra(self):
        i = self.CDRfit.currentIndex()
        self.eqs.fitSpectra(i)

def new_Ui_EQSignal_jl():
    # if QtGui.QApplication.instance() == None:
    #     app = QtGui.QApplication(sys.argv)
    # else:
    #     app = QtGui.QApplication.instance()
    return Ui_EQSignal()